// TODO:多语言文件多层结构转换为tskey
const babel = require('@babel/core');
const parser = require('@babel/parser');
const path = require('path');
const fs = require('fs');
//  原始文件
const UPLOAD_DIR = path.resolve(__dirname, './en.ts'); // 文件存储目录
//  通过babel读取文件代码
const {code} = babel.transformFileSync(UPLOAD_DIR, {});
// 查看一下
//  解析为 ast
const ast = parser.parse(code, {
  sourceType: 'module',
  plugins: ['dynamicImport'],
});

// 遍历
const traverse = require('babel-traverse').default;
const t = require('@babel/types');

let cacheParent = {};
traverse(ast, {
  ObjectProperty(nodepath, state) {
    // ObjectProperty 节点
    // 处理节点
    const {node, parent} = nodepath;
    if (t.isStringLiteral(node.value) && !cacheParent[node.key.name]) {
      console.log(node.key.name);
      cacheParent[node.key.name] = node.key.name;
    } else {
      const parentKey = cacheParent[node.key.name] || node.key.name;
      nodepath.traverse(
        {
          ObjectProperty(childPath) {
            cacheParent[childPath.node.key.name] =
              this.parentKey + '.' + childPath.node.key.name;
          },
        },
        {parentKey},
      ); // 对子树进行遍历和替换
    }
  },
});
console.log(cacheParent);
traverse(ast, {
  enter(nodepath, state) {
    // ObjectExpression 节点
    // 处理节点
    const {node, parent} = nodepath;
    if (
      node.type === 'ObjectExpression' &&
      parent.type === 'VariableDeclarator'
    ) {
      const res = createObjectNode(cacheParent);
      getCodeFile(res);
    }
  },
});
// 生成节点
function createObjectNode(nodeList) {
  const properties = [];
  Object.keys(nodeList).forEach((key) => {
    const name = t.stringLiteral(nodeList[key]);
    properties.push(t.objectProperty(name, name));
  });
  return t.objectExpression(properties);
}
// 还原为代码
function getCodeFile(ast) {
  const generate = require('@babel/generator').default;
  const resWithExport = addExport(ast);
  const res = generate(resWithExport).code;
  fs.writeFile(
    path.resolve(__dirname, './keyMap.ts'),
    res,
    {encoding: 'utf-8'},
    (err) => {
      console.log('写入完成');
    },
  );
}
function addExport(ast) {
  const template = require('@babel/template').default;
  const buildRequire = template(`
    export default %%exportDefault%%
  `);
  return buildRequire({
    exportDefault: ast,
  });
}
